#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <omp.h>

int main(){
 
  FILE * pFile;
  long lSize;
  char * buffer_left;
  char * buffer_right;
  char * buffer2_left;
  char * buffer2_right;
  int i;
  size_t result;

  
  pFile = fopen ( "shakespe.txt" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  
  buffer_left = (char*) malloc (sizeof(char)*lSize/2+2);
  if (buffer_left == NULL) {fputs ("Memory error",stderr); exit (2);}
  buffer_right = (char*) malloc (sizeof(char)*lSize/2+2);
  if (buffer_right == NULL) {fputs ("Memory error",stderr); exit (2);}
  
  buffer2_left = (char*) malloc (sizeof(char)*lSize/2+2);
  if (buffer2_right == NULL) {fputs ("Memory error",stderr); exit (2);}
  buffer2_right = (char*) malloc (sizeof(char)*lSize/2+2);
  if (buffer2_right == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:

  result = fread (buffer_left,1,lSize/2,pFile);
  if (result != lSize/2) {fputs ("Reading error 1",stderr);exit (3);}
 
  result = fread (buffer_right,1,lSize-lSize/2,pFile);
  if (result != lSize-lSize/2) {fputs ("Reading error 2",stderr);exit (3);}


  /* the whole file is now loaded in the memory buffer in 2 buffers. */

  // terminate

  fclose (pFile);


  #pragma omp  sections
  {
    
    #pragma omp section
    {
      char * pch=0;
      pch = strtok (buffer_left," \t");
      while (pch != NULL){
        strcat(buffer2_left,pch);
        pch = strtok (NULL," \t");
      }         
    }
    
    #pragma omp section
    {
      char * pch=0;
      pch = strtok (buffer_right," \t");
      while (pch != NULL){
        strcat(buffer2_right,pch);
        pch = strtok (NULL," \t");
      }
    }
  }
     
  
  free (buffer_right);
  free (buffer_left);
  
  size_t b2_l = strlen(buffer2_left);
  size_t b2_r =  strlen(buffer2_right);

    
  #pragma omp parallel for 
  for(i=0; i < b2_l ;i++){
    if(ispunct(buffer2_left[i]))
      buffer2_left[i]='\n';
  }
  #pragma omp parallel for 
  for(i=0; i < b2_r ;i++){
    if(ispunct(buffer2_right[i]))
      buffer2_right[i]='\n';
  }

  pFile = fopen ( "res2.txt" , "w" );    
  fwrite (buffer2_left , 1 , b2_l , pFile );
  fwrite (buffer2_right , 1 , b2_r , pFile );

    
  free (buffer2_left);
  free (buffer2_right);
  
  fclose (pFile);
  
  
  
  return 0;
}